import time
from machine import Pin

def run(ed, k_u, k_d, k_l, k_r, k_a, k_b):
    paddle_x = 70  # 桌子初始位置
    ball = [80, 60]  # 球初始位置
    ball_speed = [2, 2]  # 球速度
    bricks = []  # 砖块数组
    # 生成砖块
    for y in range(4):
        for x in range(8):
            bricks.append([x * 20, y * 10 + 20])
    while True:
        # 移动桌子
        if k_l.value() == 0 and paddle_x > 0:
            paddle_x -= 5
        if k_r.value() == 0 and paddle_x < 120:
            paddle_x += 5
        # 移动球
        ball[0] += ball_speed[0]
        ball[1] += ball_speed[1]
        # 边界碰撞检测
        if ball[0] <= 0 or ball[0] >= 155:
            ball_speed[0] *= -1
        if ball[1] <= 0:
            ball_speed[1] *= -1
        # 桌子碰撞检测
        if ball[1] >= 110 and paddle_x <= ball[0] <= paddle_x + 40:
            ball_speed[1] *= -1
        # 砖块碰撞检测
        for brick in bricks[:]:
            if brick[0] <= ball[0] <= brick[0] + 20 and brick[1] <= ball[1] <= brick[1] + 8:
                bricks.remove(brick)
                ball_speed[1] *= -1
                break
        # 绘制游戏画面
        ed.fill(0x0000)  # 清屏
        for brick in bricks:
            ed.fill_rect(brick[0], brick[1], 18, 6, 0x001F)  # 绘制砖块
        ed.fill_rect(paddle_x, 115, 40, 5, 0xFFFF)  # 绘制桌子
        ed.fill_rect(int(ball[0]), int(ball[1]), 5, 5, 0xF800)  # 绘制球
        ed.show()
        # 游戏结束条件
        if ball[1] > 128 or len(bricks) == 0:
            break
        time.sleep(0.02)  # 控制游戏速度
    # 游戏结束显示
    ed.fill(0x0000)  # 清屏
    ed.text("游戏结束!", 50, 50)
    ed.text("剩余砖块: {}".format(len(bricks)), 50, 70)
    ed.text("按 B 键返回", 80, 110)
    ed.show()
    # 等待按下 B 键返回
    while True:
        if k_b.value() == 0:
            time.sleep(0.2)
            return